package com.bahehe.taoyunabus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


import com.kuad.KuBanner;



import android.app.ActivityGroup;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class BusInfo extends ActivityGroup {
	
	    private static final String TAG = "BusInfo";
	    private ListView mListRouteInfo;
	    private ArrayList<HashMap<String, Object>> busInfoList = null;
	    private SimpleAdapter listItemAdapter = null;
	    private CustomBaseAdapter busInfoAdapter;
		private TextView mInputRouteTextView = null;
		private ArrayList<SearchResults> searchResults = null;
		private Button mButton1 = null;
		private Button mButton2 = null;
		private Button mButton3 = null;
		private Button mButton4 = null;
		private Button mButton5 = null;
		private Button mButton6 = null;
		private Button mButton7 = null;
		private Button mButton8 = null;
		private Button mButton9 = null;
		private Button mButton0 = null;
		private Button mButtonClear = null;
		
		
//		private String[] mArray_RouteName;
//		private String[] mArray_RouteNumber;
		
		private static String mLocation; 
		
		private String URL_GetAllBusLine = "http://124.199.77.90/Taoyuan/aspx/dyBus/BusXMLLine.aspx?Mode=4&Provider=0";		
		private String URL_GetFilterBusLine = "http://124.199.77.90/Taoyuan/aspx/dyBus/BusXMLLine.aspx?Mode=8&stopName=";	
		
		private String Location_TW = "&Lang=";
		private String Location_EN = "&Lang=En";
		
		
		
		private final static String BUS_NAME="bus_name";
		private final static String BUS_NUMBER="bus_num";
		//private final static String BUS_ROUTEID="bus_id";  
		
		private String mSearchRouteNum = "";
	
	   @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        requestWindowFeature(Window.FEATURE_NO_TITLE);  
	        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
	                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
	        setContentView(R.layout.businfo);
	        
	       
	        KuBanner banner = (KuBanner)findViewById(R.id.kuadview);
	        banner.setAPID("000000aBO");
	        
	        findViews();
	        setListensers() ;
	        
	        
	        
	        try {
	        	searchResults = GetSearchResults();
	        	System.out.println(searchResults);
	 	        busInfoAdapter = new CustomBaseAdapter(BusInfo.this, searchResults);
	 	        mListRouteInfo.setAdapter(busInfoAdapter);     
			} catch (Exception e) {
				// TODO: handle exception
			//	System.out.println("Get Error = "+e.getMessage().toString());
			//	Log.i(TAG, e.getMessage());
			}
	          
	        mListRouteInfo.setOnItemClickListener(BusRouteClickListener);
	        
	   }
	   
	   public void findViews(){
		    mInputRouteTextView = (TextView)findViewById(R.id.txtInputRoute);
			mListRouteInfo = (ListView)findViewById(R.id.listRouteResult);
			mButton1 = (Button)findViewById(R.id.buttonNum1);
			mButton2 = (Button)findViewById(R.id.buttonNum2);
			mButton3 = (Button)findViewById(R.id.buttonNum3);
			mButton4 = (Button)findViewById(R.id.buttonNum4);
			mButton5 = (Button)findViewById(R.id.buttonNum5);
			mButton6 = (Button)findViewById(R.id.buttonNum6);
			mButton7 = (Button)findViewById(R.id.buttonNum7);
			mButton8 = (Button)findViewById(R.id.buttonNum8);
			mButton9 = (Button)findViewById(R.id.buttonNum9);
			mButton0 = (Button)findViewById(R.id.buttonNum0);
			mButtonClear = (Button)findViewById(R.id.buttonNumClear);		
		}
		
		
		private void setListensers() {
			mButton1.setOnClickListener(SearchButtonClickListener);
			mButton2.setOnClickListener(SearchButtonClickListener);
			mButton3.setOnClickListener(SearchButtonClickListener);
			mButton4.setOnClickListener(SearchButtonClickListener);
			mButton5.setOnClickListener(SearchButtonClickListener);
			mButton6.setOnClickListener(SearchButtonClickListener);
			mButton7.setOnClickListener(SearchButtonClickListener);
			mButton8.setOnClickListener(SearchButtonClickListener);
			mButton9.setOnClickListener(SearchButtonClickListener);
			mButton0.setOnClickListener(SearchButtonClickListener);
			mButtonClear.setOnClickListener(ResetSearchButtonClickListener);
			
		}
		
//		View oldView;

		private AdapterView.OnItemClickListener BusRouteClickListener = new AdapterView.OnItemClickListener(){

				
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long arg3) {
				// TODO Auto-generated method stub
				
				  if (((ListView)parent).getTag() != null){

					  		((View)((ListView)parent).getTag()).setBackgroundDrawable(null);

					  }

					  ((ListView)parent).setTag(view);
					  view.setBackgroundColor(Color.rgb(102, 204, 255));
					  			//view.setBackgroundResource(R.drawable.bg_title_bustime);

				
				Object o = mListRouteInfo.getItemAtPosition(position);
				SearchResults fullObject = (SearchResults)o;
				Log.i(TAG,"Name=" +fullObject.getRoute_name() );
				Log.i(TAG,"Number=" +fullObject.getRoute_number() );

				Bundle bundle = new Bundle();
				bundle.putString(BUS_NAME, fullObject.getRoute_name());
				bundle.putString(BUS_NUMBER,fullObject.getRoute_number() );
				
				Intent intent = new Intent(BusInfo.this,BusRouteTime.class);
		    	intent.putExtras(bundle);
		    	startActivity(intent);
			}
			
		};
		
		private Button.OnClickListener ResetSearchButtonClickListener = new Button.OnClickListener(){
		
		     public void onClick(View view){  			 
		    		searchResults = GetSearchResults();
		    		mInputRouteTextView.setText("");	
		    		mSearchRouteNum = "";
		    		busInfoAdapter = new CustomBaseAdapter(BusInfo.this, searchResults);
		    		mListRouteInfo.setAdapter(busInfoAdapter);
		    		busInfoAdapter.notifyDataSetChanged();		    	
		     }
		};
		
		private Button.OnClickListener SearchButtonClickListener = new Button.OnClickListener(){
		
		     public void onClick(View view){		     
		    	 Button b = (Button)view;
		    	 String text = b.getText().toString();
		    	 mSearchRouteNum = mSearchRouteNum +  text.charAt(0);
		    	 if(mSearchRouteNum.length() <=3){			    		 
			    		 mInputRouteTextView.setText(mSearchRouteNum);			    		 
			    		 searchResults = GetSearchResults(mSearchRouteNum);
			    		 if(searchResults !=null){
			    			 busInfoAdapter = new CustomBaseAdapter(BusInfo.this, searchResults);
				    		 Log.i(TAG,"searchResults Count="+searchResults.size());
					    	 mListRouteInfo.setAdapter(busInfoAdapter);
					    	 busInfoAdapter.notifyDataSetChanged();
			    		 }			    		
		    	 }
			  
		     }
		};
		
		private String[] GetBusLine(String strURL){
			HttpGet hg = new HttpGet(strURL);
	    	HttpClient hc = new DefaultHttpClient();
	    	
	    	HttpResponse hr;
			try {
				hr = hc.execute(hg);
				if(hr.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
					String strResult = EntityUtils.toString(hr.getEntity());
					String[] strAllLines = strResult.split("\\|");
					 
					if(strAllLines.length > 1){
						String[] laststrAllLines = new String[strAllLines.length -1];
	    				for(int i=0; i<laststrAllLines.length;i++){
	    					laststrAllLines[i] = strAllLines[i];
	    					
	    				}
	    				if(laststrAllLines[0].length() > 0){
	    	//				System.out.println("laststrAllLines = " + laststrAllLines[0]);
	    					return laststrAllLines;
	    				}
	    				else
	    					return null;
					}else {
						return null;
					}
				
					
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			
		}
		
		
		private ArrayList<SearchResults> GetSearchResults(){
		     ArrayList<SearchResults> results = new ArrayList<SearchResults>();
		     String strURL;
		     String[] strAllLines;
		     
		     mLocation = getResources().getConfiguration().locale.getLanguage();
		     if(mLocation.equals("zh")){
		    	  strURL = URL_GetAllBusLine + Location_TW;
		     }else{
		    	  strURL = URL_GetAllBusLine + Location_EN;		    	
		     }
		     Log.i(TAG,strURL);
		     strAllLines = GetBusLine(strURL);
		     
		     if(strAllLines!=null){		    	 
		    	 for(String strBranch : strAllLines){		
 					String[] routeinfo = strBranch.split("\\,");
 					SearchResults sr = new SearchResults();
 					
 					 if(routeinfo[0].equals("501"))
 						 continue;
 					 if(mLocation.equals("zh"))
 						 sr.setRoute_number(routeinfo[0] + "��");
 					else
 						sr.setRoute_number(routeinfo[0]+" Line");
					sr.setRoute_name(routeinfo[1]);
					System.out.println("routeinfo[0]  = " + routeinfo[0] );
					System.out.println("routeinfo[1]  = " + routeinfo[1] );
					results.add(sr);
 				}
		     }
		     
	    // 	 Log.i(TAG,"return results");
		     return results;
	    }
		private ArrayList<SearchResults> GetSearchResults(String routeNum){
		     ArrayList<SearchResults> results = new ArrayList<SearchResults>();
		     String strURL;
		     String[] strAllLines;
		     
		     mLocation = getResources().getConfiguration().locale.getLanguage();
		     if(mLocation.equals("zh")){
		    	  strURL = URL_GetFilterBusLine + routeNum + Location_TW;
		     }else{
		    	  strURL = URL_GetFilterBusLine + routeNum + Location_EN;		    	
		     }
		     Log.i(TAG,strURL);
		     strAllLines = GetBusLine(strURL);
		   
		     if(strAllLines!=null && strAllLines.length > 0){		    	 
		    	 for(String strBranch : strAllLines){		
					String[] routeinfo = strBranch.split("\\,");
					SearchResults sr = new SearchResults();
		    		sr.setRoute_number(routeinfo[0] + "��");
					sr.setRoute_name(routeinfo[1]);		
					results.add(sr);
				}
		    	 return results;
		     }
		    

		     return null;
	    }
}
